<template>
  <view class="profile-container">
    <view class="profile-header">
      <view class="avatar-section" @tap="chooseAvatar">
        <image class="avatar" :src="userInfo.avatarUrl || '/static/default-avatar.png'" mode="aspectFill"></image>
        <view class="avatar-edit">
          <text>点击更换头像</text>
        </view>
      </view>
    </view>
    
    <view class="profile-form">
      <view class="form-item">
        <text class="label">用户名</text>
        <input class="input" v-model="userInfo.nickName" placeholder="请输入用户名" />
      </view>
      
      <view class="form-item">
        <text class="label">手机号</text>
        <input class="input" v-model="userInfo.phone" placeholder="请输入手机号" type="number" />
      </view>
      
      <view class="form-item">
        <text class="label">性别</text>
        <picker mode="selector" :value="genderIndex" :range="genderOptions" @change="onGenderChange">
          <view class="picker">{{ genderOptions[genderIndex] }}</view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="label">生日</text>
        <picker mode="date" :value="userInfo.birthday" @change="onBirthdayChange">
          <view class="picker">{{ userInfo.birthday || '请选择生日' }}</view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="label">收货地址</text>
        <view class="address-section">
          <view class="address-item" v-for="(address, index) in addresses" :key="index">
            <text class="address-text">{{ address.province }} {{ address.city }} {{ address.district }} {{ address.detail }}</text>
            <view class="address-actions">
              <text class="action-btn" @tap="editAddress(index)">编辑</text>
              <text class="action-btn delete" @tap="deleteAddress(index)">删除</text>
            </view>
          </view>
          <view class="add-address" @tap="addAddress">
            <text class="add-text">+ 添加收货地址</text>
          </view>
        </view>
      </view>
    </view>
    
    <view class="profile-actions">
      <button class="btn wechat-btn" @tap="getWechatInfo">从微信获取信息</button>
      <button class="btn save-btn" @tap="saveProfile">保存</button>
    </view>
  </view>
</template>

<script>
import api from '@/utils/api.js';

export default {
  data() {
    return {
      userInfo: {},
      genderIndex: 0,
      genderOptions: ['未知', '男', '女'],
      addresses: []
    };
  },
  onLoad() {
    this.loadUserInfo();
  },
  methods: {
    // 加载用户信息
    loadUserInfo() {
      const userInfo = uni.getStorageSync('userInfo');
      if (userInfo) {
        this.userInfo = { ...userInfo };
        
        // 设置性别选择器的值
        if (this.userInfo.gender === 'male') {
          this.genderIndex = 1;
        } else if (this.userInfo.gender === 'female') {
          this.genderIndex = 2;
        } else {
          this.genderIndex = 0;
        }
      }
      
      // 加载地址列表
      this.loadAddresses();
    },
    
    // 加载地址列表
    loadAddresses() {
      // 调用API获取地址列表
      api.getAddresses().then(res => {
        if (res.success && res.addresses) {
          this.addresses = res.addresses;
        }
      }).catch(err => {
        console.error('获取地址列表失败:', err);
        // 使用模拟数据作为后备
        this.addresses = [
          {
            id: '1',
            province: '广东省',
            city: '深圳市',
            district: '南山区',
            detail: '科技园南区',
            isDefault: true
          }
        ];
      });
    },
    
    // 选择头像
    chooseAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.userInfo.avatarUrl = res.tempFilePaths[0];
        }
      });
    },
    
    // 性别选择
    onGenderChange(e) {
      this.genderIndex = e.detail.value;
      const genderMap = ['unknown', 'male', 'female'];
      this.userInfo.gender = genderMap[this.genderIndex];
    },
    
    // 生日选择
    onBirthdayChange(e) {
      this.userInfo.birthday = e.detail.value;
    },
    
    // 从微信获取信息
    getWechatInfo() {
      uni.showLoading({
        title: '获取中...'
      });
      
      // 获取用户信息
      if (uni.getUserProfile) {
        // 新版本API
        uni.getUserProfile({
          desc: '用于完善用户资料',
          success: (res) => {
            this.userInfo.nickName = res.userInfo.nickName;
            this.userInfo.avatarUrl = res.userInfo.avatarUrl;
            this.userInfo.gender = res.userInfo.gender === 1 ? 'male' : res.userInfo.gender === 2 ? 'female' : 'unknown';
            
            // 更新性别选择器
            if (this.userInfo.gender === 'male') {
              this.genderIndex = 1;
            } else if (this.userInfo.gender === 'female') {
              this.genderIndex = 2;
            } else {
              this.genderIndex = 0;
            }
            
            uni.hideLoading();
            uni.showToast({
              title: '获取成功',
              icon: 'success'
            });
          },
          fail: (err) => {
            uni.hideLoading();
            console.error('获取用户信息失败:', err);
            uni.showToast({
              title: '获取失败',
              icon: 'none'
            });
          }
        });
      } else {
        // 旧版本API
        uni.getUserInfo({
          success: (res) => {
            this.userInfo.nickName = res.userInfo.nickName;
            this.userInfo.avatarUrl = res.userInfo.avatarUrl;
            this.userInfo.gender = res.userInfo.gender === 1 ? 'male' : res.userInfo.gender === 2 ? 'female' : 'unknown';
            
            // 更新性别选择器
            if (this.userInfo.gender === 'male') {
              this.genderIndex = 1;
            } else if (this.userInfo.gender === 'female') {
              this.genderIndex = 2;
            } else {
              this.genderIndex = 0;
            }
            
            uni.hideLoading();
            uni.showToast({
              title: '获取成功',
              icon: 'success'
            });
          },
          fail: (err) => {
            uni.hideLoading();
            console.error('获取用户信息失败:', err);
            uni.showToast({
              title: '获取失败',
              icon: 'none'
            });
          }
        });
      }
    },
    
    // 保存用户资料
    saveProfile() {
      if (!this.userInfo.nickName) {
        uni.showToast({
          title: '请输入用户名',
          icon: 'none'
        });
        return;
      }
      
      if (!this.userInfo.phone) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        });
        return;
      }
      
      // 验证手机号格式
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!phoneReg.test(this.userInfo.phone)) {
        uni.showToast({
          title: '手机号格式不正确',
          icon: 'none'
        });
        return;
      }
      
      uni.showLoading({
        title: '保存中...'
      });
      
      // 调用API保存用户信息
      api.updateUserInfo(this.userInfo).then(res => {
        if (res.success) {
          // 更新本地存储
          uni.setStorageSync('userInfo', this.userInfo);
          
          uni.hideLoading();
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          });
          
          // 返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.hideLoading();
          uni.showToast({
            title: res.message || '保存失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        uni.hideLoading();
        console.error('保存用户信息失败:', err);
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        });
      });
    },
    
    // 添加地址
    addAddress() {
      uni.navigateTo({
        url: '/pages/address/address?mode=add'
      });
    },
    
    // 编辑地址
    editAddress(index) {
      const address = this.addresses[index];
      uni.navigateTo({
        url: `/pages/address/address?mode=edit&id=${address.id}`
      });
    },
    
    // 删除地址
    deleteAddress(index) {
      uni.showModal({
        title: '提示',
        content: '确定要删除这个地址吗？',
        success: (res) => {
          if (res.confirm) {
            this.addresses.splice(index, 1);
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });
          }
        }
      });
    }
  }
};
</script>

<style lang="scss">
.profile-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 120rpx;
}

.profile-header {
  background-color: #fff;
  padding: 40rpx;
  display: flex;
  justify-content: center;
  margin-bottom: 20rpx;
  
  .avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    
    .avatar {
      width: 160rpx;
      height: 160rpx;
      border-radius: 50%;
    }
    
    .avatar-edit {
      position: absolute;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.5);
      color: white;
      font-size: 24rpx;
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
    }
  }
}

.profile-form {
  background-color: #fff;
  
  .form-item {
    display: flex;
    flex-direction: column;
    padding: 30rpx 40rpx;
    border-bottom: 1px solid #f0f0f0;
    
    .label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 20rpx;
    }
    
    .input {
      font-size: 32rpx;
      color: #333;
      border: 1px solid #e0e0e0;
      border-radius: 8rpx;
      padding: 20rpx;
      background-color: #f9f9f9;
    }
    
    .picker {
      font-size: 32rpx;
      color: #333;
      border: 1px solid #e0e0e0;
      border-radius: 8rpx;
      padding: 20rpx;
      background-color: #f9f9f9;
    }
    
    .address-section {
      width: 100%;
      
      .address-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx;
        margin-bottom: 20rpx;
        background-color: #f9f9f9;
        border-radius: 8rpx;
        
        .address-text {
          font-size: 28rpx;
          color: #333;
          flex: 1;
        }
        
        .address-actions {
          display: flex;
          
          .action-btn {
            font-size: 24rpx;
            color: #07c160;
            margin-left: 20rpx;
            
            &.delete {
              color: #ff4d4f;
            }
          }
        }
      }
      
      .add-address {
        padding: 20rpx;
        border: 1px dashed #ccc;
        border-radius: 8rpx;
        text-align: center;
        
        .add-text {
          font-size: 28rpx;
          color: #999;
        }
      }
    }
  }
}

.profile-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 40rpx;
  display: flex;
  flex-direction: column;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  
  .btn {
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 40rpx;
    font-size: 32rpx;
    text-align: center;
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    &.wechat-btn {
      background-color: #07c160;
      color: white;
    }
    
    &.save-btn {
      background-color: #ff9500;
      color: white;
    }
  }
}
</style>